<template>
    <section class="todo">
        <input 
            type="text" 
            class="todo_input" 
            @keyup.enter="todoInput" 
            placeholder="接下去要做什么？" 
            autofocus="autofocus"
        >
        <item 
            v-for="todo of filteredTodos" 
            :todo="todo" 
            :key="todo.id"
            @deleteItem="delItem"
        ></item>
        <tabs 
            :todoItems="todoItems" 
            @toggleStatus="toggleStatus"
            @clearAllTodos="clearAllTodos"
        />
    </section>
</template>

<script>
import Item from './item.vue'
import Tabs from './tabs.vue'

// 随机生成不重复的任务id号
function GenNonDuplicateID(){
  return Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)
}
export default {
    data() {
        return {
            todoItems: [
                {
                    id: 0,
                    checked: false,
                    content: '任务1'
                }
            ],
            filteredStatus: 'all'
        }
    },
    components: {
        Item,
        Tabs
    },
    computed: {
        filteredTodos() {
            if (this.filteredStatus === 'all') {
                return this.todoItems
            }
            let checked = this.filteredStatus === 'completed'
            return this.todoItems.filter(todo => checked === todo.checked)
        }
    },
    methods: {
        todoInput (e) {
            if (!e.target.value) {
                alert('任务内容不能为空')
                return 
            }
            this.todoItems.unshift({
                id: GenNonDuplicateID(),
                checked: false,
                content: e.target.value
            })
            e.target.value = ''
        },
        delItem (target) {
            this.todoItems.splice(target, 1)
        },
        toggleStatus(status) {
            this.filteredStatus = status
            // console.log(this.filteredStatus);
        },
        clearAllTodos() {
            this.todoItems = this.todoItems.filter(todo => !todo.checked)
        }
    }
}
</script>

<style lang="stylus" scoped>
.todo {
    width 600px
    margin 0 auto 
    background-color white
    display flex
    flex-direction column
    align-items center
    box-shadow 0 0 5px #666
    .todo_input {
        width 100%
        height 60px
        font-size 20px
        border 0 
        border-bottom 2px solid #999
        padding-left 50px
        box-sizing border-box
	    outline-width: 0px 
    }  
}
</style>